import { ThreadWorker } from 'poolifier';
import { parentPort } from 'worker_threads';
import { initRingBuffer, writeToRingBuffer, readFromRingBuffer } from './utils';

class MemBridgeWorker extends ThreadWorker {
  constructor() {
    super({
      initMemBridge: (payload: any) => {
        const { capacity, dllPath, dllName } = payload;
        initRingBuffer(capacity, dllPath, dllName);
        this.startReadingRingBuffer(capacity);
      },
      writeMsg: (payload: any) => {
        const { funcName, fno, data } = payload;
        writeToRingBuffer(funcName, fno, data);
      },
    });
  }

  startReadingRingBuffer(bufferSize = 1024, intervalMs = 10) {
    const intervalId = setInterval(() => {
      try {
        const result = readFromRingBuffer(bufferSize);
        if (result === null) {
          // console.warn(`从通道 ${channelId} 未读取到数据`);
          return;
        }
        const res = {
          funcName: result.funcName,
          data: result.data,
          fno: result.fno,
        };
        // console.log('读取到的数据:', res);
        parentPort.postMessage(res);
      } catch (error) {
        console.error(`读取数据出错:`, error);
      }
    }, intervalMs);

    // 返回 interval ID，以便后续停止读取
    return intervalId;
  }
}

module.exports = new MemBridgeWorker();
